package com.dongdongshop.controller;

import com.dongdongshop.data.Result;
import com.dongdongshop.enums.ResultEnum;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.TbUserService;
import com.dongdongshop.shiro.ShiroUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

@Controller
@RequestMapping("register")
public class RegisterController {
    @DubboReference(check = false)
    private TbUserService service;

    @RequestMapping("toRegister")
    public String toRegister(){
        return "register";
    }

    @Autowired
    private RocketMQTemplate mqTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @RequestMapping("registerUser")
    @ResponseBody
    public Result registerUser(String phone){
        try {
            mqTemplate.convertAndSend("2204dk-topic",phone);
            return Result.OK();
        }catch (Exception e){
            return Result.ERROR();
        }
    }
    @RequestMapping("addUser")
    @ResponseBody
    public Result addUser(TbUser user,String code){
        try {
            if(!redisTemplate.hasKey(user.getPhone())){
                return Result.response(ResultEnum.MESSAGE_CODE_KILL);
            }
            String key = (String) redisTemplate.opsForValue().get(user.getPhone());
            if(!key.equals(code)){
                return Result.response(ResultEnum.MESSAGE_CODE_ERROR);
            }
            TbUser user2 = service.selectByUsername(user.getUsername());
            if(user2 != null){
                return new Result(90,"账号已被注册");
            }
            String salt = ShiroUtils.generateSalt(6);
            String s = ShiroUtils.encryptPassword("MD5", user.getPassword(), salt, 3);
            user.setPassword(s);
            user.setSalt(salt);
            user.setCreated(new Date());
            user.setUpdated(new Date());
            service.addUser(user);
            return Result.OK();
        }catch (Exception e){
            return Result.ERROR();
        }
    }

}
